from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from config import get_settings

# 数据库地址
database_url: str = get_settings().database_url
# 数据库端口
database_port: int = get_settings().database_port
# 数据库用户名
database_user: str = get_settings().database_user
# 数据库密码
database_password: str = get_settings().database_password
# 数据库名
database_name: str = get_settings().database_name

SQLALCHEMY_DATABASE_URL = (f"mysql+pymysql://{database_user}:{database_password}@{database_url}:{database_port}/"
                           f"{database_name}?charset=utf8mb4")
# 3.创建 SQLAlchemy 引擎
engine = create_engine(SQLALCHEMY_DATABASE_URL)
# 4.创建一个SessionLocal 数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 5.创建一个Base类
Base = declarative_base()


# 依赖
def get_db():
    db = None  # 初始化 db 变量
    try:
        db = SessionLocal()
        yield db
    finally:
        if db:
            db.close()
